<template>
  <el-card class="personal-info">
    <template #header>
      <div class="card-header">
        <span>基本信息</span>
        <el-button type="primary" @click="showEditDialog = true">编辑信息</el-button>
      </div>
    </template>

    <el-descriptions :column="2" border>
      <el-descriptions-item label="姓名">{{ user.realName || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="用户名">{{ user.username || '无' }}</el-descriptions-item>
      <el-descriptions-item label="性别">
        {{ user.gender === 1 ? '男' : user.gender === 2 ? '女' : user.gender === 0 ? '未知' : '未设置' }}
      </el-descriptions-item>
      <el-descriptions-item label="身份证号">{{ user.idCard || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="年龄">{{ calculateAge() || '未知' }}</el-descriptions-item>
      <el-descriptions-item label="联系方式">{{ user.phone || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="出生日期">
        {{ user.birthDate }}
      </el-descriptions-item>
      <el-descriptions-item label="居住地址">{{ user.address || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="邮箱">{{ user.email || '无' }}</el-descriptions-item>
    </el-descriptions>

    <el-divider content-position="left">健康信息</el-divider>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="身高(cm)">{{ userInfo.height || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="体重(kg)">{{ userInfo.weight || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="BMI">{{ calculateBMI() || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="血型">{{ userInfo.bloodType || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="病史记录" :span="2">{{ userInfo.medicalHistory || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="过敏史" :span="2">{{ userInfo.allergyHistory || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="生活习惯" :span="2">{{ userInfo.dailyHabits || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="居住状况" :span="2">{{ userInfo.livingCondition || '未设置' }}</el-descriptions-item>
    </el-descriptions>

    <el-divider content-position="left">紧急联系人</el-divider>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="姓名">{{ userInfo.emergencyContactName || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="电话">{{ userInfo.emergencyContactPhone || '未设置' }}</el-descriptions-item>
      <el-descriptions-item label="关系" :span="2">{{ userInfo.emergencyContactRelation || '未设置' }}</el-descriptions-item>
    </el-descriptions>
  </el-card>

  <!-- 编辑信息对话框 -->
  <el-dialog v-model="showEditDialog" title="编辑个人信息" width="50%">
    <el-tabs v-model="activeEditTab">
      <el-tab-pane label="基本信息" name="basic">
        <el-form :model="editUser" label-width="100px" label-position="left">
          <el-form-item label="昵称" prop="username" required>
            <el-input v-model="editUser.username" placeholder="请输入昵称" clearable />
          </el-form-item>
          <el-form-item label="姓名" prop="realName" required>
            <el-input v-model="editUser.realName" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="密码" prop="password" required>
            <el-input v-model="editUser.password" type="password" show-password placeholder="请输入密码" clearable />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="editUser.gender" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker v-model="editUser.birthDate" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="editUser.idCard" placeholder="请输入18位身份证号" maxlength="18" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="editUser.phone" placeholder="请输入11位手机号码" maxlength="11" clearable />
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="editUser.email" placeholder="请输入电子邮箱" clearable />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editUser.address" placeholder="请输入详细地址" clearable />
          </el-form-item>
          <el-form-item label="头像" prop="avatarUrl">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarUpload"
            >
              <img v-if="editUser.avatarUrl" :src="editUser.avatarUrl" class="avatar">
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="健康信息" name="health">
        <el-form :model="editUserInfo" label-width="100px" label-position="left">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身高(cm)">
                <el-input-number v-model="editUserInfo.height" placeholder="请输入身高" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="体重(kg)">
                <el-input-number v-model="editUserInfo.weight" placeholder="请输入体重" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="血型">
            <el-select v-model="editUserInfo.bloodType" placeholder="请选择血型" style="width: 100%">
              <el-option label="请选择血型" value="" />
              <el-option label="A型" value="A" />
              <el-option label="B型" value="B" />
              <el-option label="AB型" value="AB" />
              <el-option label="O型" value="O" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>

          <el-form-item label="病史记录">
            <el-input v-model="editUserInfo.medicalHistory" type="textarea" :rows="3" placeholder="请输入病史记录" />
          </el-form-item>

          <el-form-item label="过敏史">
            <el-input v-model="editUserInfo.allergyHistory" type="textarea" :rows="3" placeholder="请输入过敏史" />
          </el-form-item>

          <el-form-item label="生活习惯">
            <el-input v-model="editUserInfo.dailyHabits" type="textarea" :rows="3" placeholder="请输入生活习惯" />
          </el-form-item>

          <el-form-item label="居住状况">
            <el-input v-model="editUserInfo.livingCondition" type="textarea" :rows="3" placeholder="请输入居住状况描述" />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="紧急联系人" name="emergency">
        <el-form :model="editUserInfo" label-width="120px" label-position="left">
          <el-form-item label="紧急联系人姓名">
            <el-input v-model="editUserInfo.emergencyContactName" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="紧急联系人电话">
            <el-input v-model="editUserInfo.emergencyContactPhone" placeholder="请输入电话号码" maxlength="11" show-word-limit />
          </el-form-item>

          <el-form-item label="紧急联系人关系">
            <el-input v-model="editUserInfo.emergencyContactRelation" placeholder="例如：儿子、女儿等" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="showEditDialog = false">取消</el-button>
      <el-button type="primary" @click="saveUserInfo">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from "axios";

const userString = ref({
  token : localStorage.getItem('token')
})

const user = ref({
  userId: null,
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  avatarUrl: '',
  idCard: '',
  gender: null,
  birthDate: null,
  address: ''
})

const userInfo = ref({
  height: null,
  weight: null,
  bloodType: '',
  medicalHistory: '',
  allergyHistory: '',
  medicationCondition: '',
  emergencyContactName: '',
  emergencyContactPhone: '',
  emergencyContactRelation: '',
  livingCondition: '',
  dailyHabits: ''
})

const editUser = ref({...user.value})
const editUserInfo = ref({...userInfo.value})
const showEditDialog = ref(false)
const activeEditTab = ref('basic')

//获取用户信息
const userStr = localStorage.getItem('user');
const userData = JSON.parse(userStr);


const calculateBMI = () => {
  if (!userInfo.value.height || !userInfo.value.weight) return null
  const heightInM = userInfo.value.height / 100
  const bmi = (userInfo.value.weight / (heightInM * heightInM)).toFixed(1)
  return bmi
}

const calculateAge = () => {
  if (!user.value.birthDate) return '未知'
  const birthDate = new Date(user.value.birthDate)
  if (isNaN(birthDate.getTime())) return '日期格式错误'
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age
}

// const token = localStorage.getItem('token');
const loadUserData = () => {
  axios.get(`${BASE_URL}/api/v1/admins/detail`, {
    params: {
      //userId: getUser().userId
      userId:userData.user.userId,
    },
    headers: {
      Authorization: `Bearer ${token}`
    }
  }).then(response => {
    if (response.data.code === 2000) {
      user.value = response.data.data;
      editUser.value = {...user.value}
    } else {
      console.log('获取用户基本信息失败:', response.data);
    }
  }).catch(error => {
    console.error('获取用户基本信息出错:', error);
  })
  axios.get(`${BASE_URL}/api/v1/elderly/getInfo`, {
    params: {
      // userId: getUser().userId
      userId: userData.user.userId
    }
  }).then(response => {
    if (response.data.code === 2000) {
      userInfo.value = response.data.data;
      editUserInfo.value = {...userInfo.value}
    } else {
      console.log('获取用户信息失败:', response.data);
    }
  }).catch(error => {
    console.error('获取用户信息出错:', error);
  })
}

const saveUserInfo = async () => {
  try {
    console.log("修改的用户生日："+editUser.value.birthDate)
    // 使用Promise.all等待所有请求完成
    const [basicRes, healthRes] = await Promise.all([
      axios.post(`${BASE_URL}/api/v1/admins/update`, editUser.value),
      axios.post(`${BASE_URL}/api/v1/elderly/updateInfo`, editUserInfo.value)
    ]);

    // 统一检查响应状态
    if (basicRes.data.code === 2000 && healthRes.data.code === 2000) {
      // 更新本地数据
      // user.value = {...editUser.value};
      // console.log("保存的用户生日："+user.value.birthDate)
      // userInfo.value = {...editUserInfo.value};
      loadUserData();

      ElMessage.success('信息保存成功');
      showEditDialog.value = false;
    } else {
      // 处理部分失败情况
      const errors = [
        basicRes.data.code !== 2000 && `基本信息: ${basicRes.data.message}`,
        healthRes.data.code !== 2000 && `健康信息: ${healthRes.data.message}`
      ].filter(Boolean);

      ElMessage.error(`保存失败: ${errors.join('; ')}`);
    }
  } catch (error) {
    console.error('保存出错:', {
      config: error.config,
      response: error.response?.data,
      message: error.message
    });

    ElMessage.error(`请求失败: ${error.response?.data?.message || error.message}`);
  }
};

const handleAvatarUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    editUser.value.avatarUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

onMounted(() => {
  loadUserData()
})
</script>

<style scoped>
.personal-info {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.personal-info:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.avatar-uploader :deep(.el-upload) {
  border: 2px dashed rgba(64, 158, 255, 0.3);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.2);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #c0c4cc;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border-radius: 50%;
  background: rgba(240, 242, 245, 0.8);
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.info-item {
  margin-bottom: 16px;
  padding: 12px 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  transition: all 0.2s;
}

.info-item:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.info-label {
  font-weight: 500;
  color: #5e6d82;
  margin-bottom: 4px;
  font-size: 14px;
}

.info-content {
  font-size: 16px;
  color: #2c3e50;
  word-break: break-word;
}

@media (max-width: 768px) {
  .personal-info {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .avatar-uploader {
    margin-bottom: 16px;
  }

  .info-item {
    padding: 10px 12px;
  }
}
</style>